﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
public class SkinMeshLOD:MonoBehaviour
{
    public static Camera MainCamera;
    public SkinnedMeshRenderer[] skinnedMeshes;
    public SkinQuality skinQuality = SkinQuality.Auto;
    public int MinQuality = 1;
    public int MidQuality = 2;
    public int MaxQuality = 4;
    /// <summary>
    /// 距离的平方
    /// </summary>
    public float DistanceLevel1 = 25;
    /// <summary>
    /// 距离的平方
    /// </summary>
    public float DistanceLevel2 = 100;
    /// <summary>
    /// 检测频率
    /// </summary>
    int CheckFrequency = 0;
    private void Awake()
    {
        MainCamera = Camera.main;
    }
    private void Update()
    {
        CheckFrequency++;
        if ((CheckFrequency % 3) == 0)//每3帧检定一次
            if (MainCamera != null)
            {
                if (skinnedMeshes != null)
                {
                    SkinQuality quality = (SkinQuality)DevicePerformanceUtil.qualityLevel;
                    if(skinQuality!=SkinQuality.Auto)
                    {
                        if (MainCamera.orthographic)
                        {
                            quality = (SkinQuality)MaxQuality;
                        }
                        else
                        {
                            var p = (transform.position - MainCamera.transform.position).sqrMagnitude;
                            if (p >= DistanceLevel2)
                            {
                                quality = (SkinQuality)MinQuality;
                            }
                            else if (p >= DistanceLevel1)
                            {
                                quality = (SkinQuality)MidQuality;
                            }
                            else
                            {
                                quality = (SkinQuality)MaxQuality;
                            }
                        }
                    }
                    for (int i = 0; i < skinnedMeshes.Length; i++)
                    {
                        skinnedMeshes[i].quality = quality;
                    }
                }
            }
    }
}
